
import http.cookiejar
from urllib import request
#获取opener
def getOpener(head, cookie):
    #设置cookide处理器，从服务器下载cookie到本地，并在请求时附带上cookie
    pro = request.HTTPCookieProcessor(cookie)       #cookies处理器
    opener = request.build_opener(pro)          #构建opener
    header = []
    for key, value in head.items():
        elem = (key,value)
        header.append(elem)
    opener.addheaders = header
    return opener

import urllib.parse
#登录
def login(id, pa):
    post = {            #表单信息
        'mode': 'login',
        'return_to': '/',
        'pixiv_id': id,
        'pass': pa,
        'skip': 1
    }
    #http报头信息
    header = {
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Accept-Language": "zh-CN,zh;q=0.8",
        "Connection": "keep-alive",
        "Host": "www.pixiv.net",
        "Referer": "http://www.pixiv.net/",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2623.110 Safari/537.36"
    }
    #登录地址
    url = 'http://www.pixiv.net/login.php'
    #表单信息编码
    postdata = urllib.parse.urlencode(post).encode()

    cj = http.cookiejar.MozillaCookieJar()
    #获取opener
    opener = getOpener(header, cj)
    #http响应
    response = opener.open(url, postdata)
    #返回文本信息
    return response.read(), cj

#保存至文件
def saveFile(path, data):
    with open(path, 'wb') as f:
        f.write(data)

#将cookie保存到本地
def saveCookie(id, ps):
    data, cookie = login(id, ps)
    #saveFile('login.html', data)
    cookie.save('cookie.txt', ignore_discard=True, ignore_expires=True)

#获取cookie
def loadCookie():
    cookie = http.cookiejar.MozillaCookieJar()
    cookie.load('cookie.txt')           #加载cookie，使变量cookie有值
    return cookie